package com.konsung.ksdc.manager.appmain;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.IpPopupWindow;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.user.ForgetPassCheckActivity;
import com.konsung.ksdc.manager.user.RegisterCheckActivity;
import com.konsung.ksdc.service.MqttService;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * d登录注册界面
 */
public class LoginActivity extends Activity implements View.OnClickListener {

    public static final String CURRENT_EMPID = "currentEmpid";
    public static final String CHECK_TYPE = "check_type";
    public static final int REGISTER = 101;
    public static final int CHANGE_PWD = 102;
    public static final int CHANGE_PHONE = 103;
    private static final int PORT_RANGE = 65535; //端口范围
    @Bind(R.id.username_ed)
    EditText etUserName;
    @Bind(R.id.password_ed)
    EditText etPassWord;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @Bind(R.id.btn_no_account)
    Button btnNoAccount;
    @Bind(R.id.ll_logining)
    LinearLayout llLogining;
    @Bind(R.id.iv_loading)
    ImageView ivLoading;
    @Bind(R.id.iv_checked)
    CheckBox ivChecked;
    private boolean isLogining = false; // 当前是否正在处理登录的网络请求
    private IpPopupWindow popupWindow;
    private Dialog dialog;
    private ObjectAnimator animator;
    private String registeredName; //已注册账号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //设置为无标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置为全屏模式
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);

        boolean isAutoLogin = PreferenceUtils.getBoolean(this, Constants.AUTO_LOGIN, false);
        String userData = PreferenceUtils.getString(this, Constants.USER_DATA, null);
        if (isAutoLogin && StringUtils.isNotEmpty(userData)) {
            autoLogin(userData);
            return;
        }

        initView();
    }

    /**
     * 自动登录
     * @param userData 用户数据
     */
    private void autoLogin(String userData) {
        String popIp = PreferenceUtils.getString(this, Constants.LOGIN_POP_IP, Constants
                .LOGIN_POP_IP);
        //如果没有设置，默认显示
        if (!popIp.equals(Constants.LOGIN_POP_IP)) {
            NetConfig.serverIP = popIp;
        }
        String popPort = PreferenceUtils.getString(this, Constants.LOGIN_POP_PORT, Constants
                .LOGIN_POP_PORT);
        //如果没有设置，默认显示
        if (!popPort.equals(Constants.LOGIN_POP_PORT)) {
            NetConfig.port = popPort;
        }
        NetConfig.picUrl = NetConfig.getServerUrl() + "ksdc-web/" +
                "download/downloadImage?fileName=";
        NetConfig.mqttSserverIp = NetConfig.serverIP;
        MqttService.mqttClient.connectionString = "tcp://" + NetConfig.mqttSserverIp +
                ":1883";
        RegisterUserNetBean user = new Gson().fromJson(userData,
                RegisterUserNetBean.class);
        NetConfig.currentUser = user;
        NetConfig.currentEmpid = user.getEmpId();

        Intent intent1 = new Intent(LoginActivity.this, LauncherActivity.class);
        intent1.putExtra(CURRENT_EMPID, user.getEmpId());
        startActivity(intent1);
        finish();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        ivChecked.setChecked(PreferenceUtils.getBoolean(this, Constants.CHECKED,
                false));
        etUserName.setText(PreferenceUtils.getString(this, Constants.USERNAME,
                ""));
        etPassWord.setText(PreferenceUtils.getString(this, Constants.PASSWORD,
                ""));
        btnLogin.setOnClickListener(this);
        tvForgetPwd.setOnClickListener(this);
        btnNoAccount.setOnClickListener(this);
        llLogining.setVisibility(View.GONE);

        animator = ObjectAnimator.ofFloat(ivLoading,
                "rotation", 0f, 360 * 5f);
        animator.setDuration(5000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                // ### 点击登录 ###
                final String name = etUserName.getText().toString();
                final String pwd = etPassWord.getText().toString();

                if (StringUtils.isEmpty(name)) {
                    ToastUtils.toastContent(this, getString(R.string.tip_username_null));
                    return;
                }
                if (StringUtils.isEmpty(pwd)) {
                    Toast.makeText(this, getString(R.string.tip_password_null),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!RequestUtils.checkNetwork(LoginActivity.this)) {
                    Toast.makeText(this, getString(R.string.tip_check_net),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                //在此判断是否为admin用户登录
                if (name.equals(Constants.ADMIN) && pwd.equals(Constants.PWD)) {
                    //
                    showIpSelectDialog(name, pwd);
                    return;
                }
                String popIp = PreferenceUtils.getString(this, Constants.LOGIN_POP_IP, Constants
                        .LOGIN_POP_IP);
                //如果没有设置，默认显示
                if (!popIp.equals(Constants.LOGIN_POP_IP)) {
                    NetConfig.serverIP = popIp;
                }
                String popPort = PreferenceUtils.getString(this, Constants.LOGIN_POP_PORT, Constants
                        .LOGIN_POP_PORT);
                //如果没有设置，默认显示
                if (!popPort.equals(Constants.LOGIN_POP_PORT)) {
                    NetConfig.port = popPort;
                }
                //重新赋值
                NetConfig.mqttSserverIp = NetConfig.serverIP;
                NetConfig.picUrl = NetConfig.getServerUrl() + "ksdc-web/" +
                        "download/downloadImage?fileName=";
                MqttService.mqttClient.connectionString = "tcp://" + NetConfig.mqttSserverIp +
                        ":1883";
                login(name, pwd);

                break;
            case R.id.btn_no_account:
                // ### 注册页面 ###
                Intent intent2 = new Intent(this, RegisterCheckActivity.class);
                intent2.putExtra(CHECK_TYPE, REGISTER);
                startActivity(intent2);
                break;
            case R.id.tv_forget_pwd:
                Intent intent = new Intent(LoginActivity.this, ForgetPassCheckActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 超级管理弹dialog
     * @param name 用户账号
     * @param pwd 密码
     */
    private void showIpSelectDialog(String name, String pwd) {
        popupWindow = new IpPopupWindow(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //替换全局变量的端口
                NetConfig.serverIP = popupWindow.getIp();
                NetConfig.port = popupWindow.getPort();
                if (Integer.parseInt(NetConfig.port) > PORT_RANGE) {
                    ToastUtils.toastContent(LoginActivity.this, getString(R.string.error_port));
                    return;
                }
                //保存ip和port
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                NetConfig.picUrl = NetConfig.getServerUrl() + "ksdc-web/" +
                        "download/downloadImage?fileName=";
                NetConfig.mqttSserverIp = NetConfig.serverIP;
                MqttService.mqttClient.connectionString = "tcp://" + NetConfig.mqttSserverIp +
                        ":1883";
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 根据输入的帐号和密码进行登录操作
     * @param name 名字
     * @param pwd 密码
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void login(final String name, final String pwd) {
        if (isLogining) {
            return;
        }
        llLogining.setVisibility(View.VISIBLE);
        if (animator != null) {
            animator.start();
        }
        isLogining = true;

        String deviceCode = PreferenceUtils.getString(this, Constants.DEVICE_CODE);

        RequestUtils.login(name, pwd, deviceCode, new RequestCallback() {

            @Override
            public void onError(Call call, Exception e) {

                if (animator != null) {
                    animator.pause();
                }

                ToastUtils.toastContent(LoginActivity.this, getString(R.string
                        .chat_unconnect));

                llLogining.setVisibility(View.GONE);

                isLogining = false;
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                if (animator != null) {
                    animator.pause();
                }
                llLogining.setVisibility(View.GONE);

                isLogining = false;
                if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                    Toast.makeText(LoginActivity.this, getString(R.string
                                    .tip_login_success) + "",
                            Toast.LENGTH_SHORT).show();

                    RegisterUserNetBean user = responseBean.getEntity(RegisterUserNetBean.class);

                    NetConfig.currentUser = user;
                    NetConfig.currentUser = user;
                    NetConfig.currentEmpid = user.getEmpId();
                    //保存账户和密码
                    PreferenceUtils.putString(LoginActivity.this, Constants.USERNAME, name);
                    if (ivChecked.isChecked()) {
                        PreferenceUtils.putString(LoginActivity.this, Constants.PASSWORD, pwd);
                        PreferenceUtils.putBoolean(LoginActivity.this, Constants.CHECKED, true);
                    } else {
                        PreferenceUtils.putBoolean(LoginActivity.this, Constants.CHECKED, false);
                        PreferenceUtils.putString(LoginActivity.this, Constants.PASSWORD, "");
                    }

                    // 写入自动登录
                    PreferenceUtils.putBoolean(LoginActivity.this, Constants.AUTO_LOGIN, true);
                    // 写入用户数据
                    String userData = new Gson().toJson(user);
                    PreferenceUtils.putString(LoginActivity.this, Constants.USER_DATA, userData);

                    // 登录成功后跳转到消息推送Activity
                    Intent intent1 = new Intent(LoginActivity.this, LauncherActivity.class);
                    intent1.putExtra(CURRENT_EMPID, user.getEmpId());
                    startActivity(intent1);
                    finish();
                } else {
                    ToastUtils.toastContent(LoginActivity.this, getString(R.string.login_fail));
                }
            }
        });
    }
}
